package com.huaxin.hxmodulemqtt.config;

import com.huaxin.hxmodulemqtt.models.MqttProperties;
import com.huaxin.hxmodulemqtt.service.MqttMessageService;
import org.eclipse.paho.client.mqttv3.MqttConnectOptions;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.integration.channel.DirectChannel;
import org.springframework.integration.config.EnableIntegration;
import org.springframework.integration.mqtt.core.DefaultMqttPahoClientFactory;
import org.springframework.integration.mqtt.core.MqttPahoClientFactory;
import org.springframework.integration.mqtt.inbound.MqttPahoMessageDrivenChannelAdapter;
import org.springframework.integration.mqtt.support.DefaultPahoMessageConverter;
import org.springframework.messaging.MessageChannel;
import org.springframework.messaging.MessageHandler;

import javax.net.ssl.SSLContext;

@Configuration
@EnableIntegration
public class MqttSubscriberConfig {

    private final MqttProperties mqttProperties;
    private final MqttMessageService mqttMessageService;

    public MqttSubscriberConfig(MqttProperties mqttProperties,
                                MqttMessageService mqttMessageService) {
        this.mqttProperties = mqttProperties;
        this.mqttMessageService = mqttMessageService;
    }

    /**
     * MQTT 客户端工厂
     */
    @Bean
    public MqttPahoClientFactory mqttClientFactory() {
        DefaultMqttPahoClientFactory factory = new DefaultMqttPahoClientFactory();
        MqttConnectOptions options = new MqttConnectOptions();

        options.setServerURIs(new String[]{mqttProperties.getHost()});
        options.setUserName(mqttProperties.getUsername());
        options.setPassword(mqttProperties.getPassword().toCharArray());
        options.setAutomaticReconnect(true);
        options.setCleanSession(false);  // 保留会话
        options.setConnectionTimeout(10);
        options.setKeepAliveInterval(20);

        factory.setConnectionOptions(options);
        return factory;
    }

    /**
     * 入站通道：接收 MQTT 消息
     */
    @Bean
    @Qualifier("mqttInputChannel")
    public MessageChannel mqttInputChannel() {
        return new DirectChannel();
    }

    /**
     * MQTT 入站适配器（订阅消息）
     */
    @Bean
    public MqttPahoMessageDrivenChannelAdapter mqttMessageDrivenChannelAdapter() {
        MqttPahoMessageDrivenChannelAdapter adapter =
                new MqttPahoMessageDrivenChannelAdapter(
                        mqttProperties.getClientId(),           // 动态 clientId
                        mqttClientFactory(),
                        mqttProperties.getDefaultTopic()        // 支持通配符
                );

        adapter.setCompletionTimeout(5000);
        adapter.setConverter(new DefaultPahoMessageConverter());
        adapter.setQos(mqttProperties.getQos());
        adapter.setManualAcks(false);
        adapter.setOutputChannel(mqttInputChannel());

        return adapter;
    }

    /**
     * 消息处理器：绑定到通道
     */
    @Bean
    @Qualifier("mqttMessageHandler")
    public MessageHandler mqttMessageHandler() {
        return mqttMessageService; // 使用你的服务
    }
}